package leetcode100;

// TODO 链表相加 | 双指针 【-】 两数相加
// TODO https://leetcode.cn/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode-solution/

public class lc100_0002 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(), p = head;
        int sign = 0; // 进位

        while (l1 != null || l2 != null) {
            int v1 = 0, v2 = 0;
            if (l1 != null) {
                v1 = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                v2 = l2.val;
                l2 = l2.next;
            }
            int sum = v1 + v2 + sign;
            sign = sum / 10;
            p.next = new ListNode(sum % 10);
            p = p.next;
        }

        if (sign != 0)
            p.next = new ListNode(sign);

        return head.next;
    }

}